package echo.service.impl;


import echo.exception.BusinessException;
import echo.service.OrderRepository;
import echo.vo.Item;
import echo.vo.ItemType;
import echo.vo.Order;
import echo.vo.OrderStatus;

import java.time.Duration;
import java.time.LocalDateTime;
import java.time.LocalTime;
import java.util.List;
import java.util.Map;
import java.util.UUID;
import java.util.stream.Collectors;

/**
 * 订单服务具体实现
 */
public class SimpleOrderService extends BaseOrderService {


    public SimpleOrderService(OrderRepository repository) {
        super(repository);
    }
    @Override
    public Order createOrder(List<Item> items, boolean isVIP, LocalDateTime currentTime) {
    validateItems(items);
    // 2. 处理时间敏感商品
    List<Item> filteredItems = filterTimeSensitiveItems(items, currentTime.toLocalTime());

    // 3. 应用业务规则校验
    validateBusinessRules(filteredItems);

    // 4. 计算价格
    double totalPrice = calculateTotalPrice(filteredItems, isVIP);

    // 5. 构建并保存订单
        // 4. 构建订单
        Order order = new Order(
                UUID.randomUUID().toString(),
                filteredItems,
                OrderStatus.CREATED,
                totalPrice,
                currentTime
        );

        repository.save(order);
        return order;
    }



    protected void validateItems(List<Item> items) {
        if (items == null || items.isEmpty()) {
            throw new BusinessException(BusinessException.ErrorTyle.LEST_ORDER);
        }
        if (items.size() > 5) {
            throw new BusinessException(BusinessException.ErrorTyle.TOO_MANY_ITEMS);
        }
    }

//    private String getremark (List<Item> filteredItems, List<Item> orgin){
//        StringBuilder builder=new StringBuilder();
//        if (Item item :orgin){
//            if (!filteredItems.contains(Item)){
//                builder.append(Item.getname()).append("商品yi");
//            }
//        }
//    }
    // 下午3点后禁止售卖冰咖啡
    protected List<Item> filterTimeSensitiveItems(List<Item> items, LocalTime currentTime) {
        LocalTime now=LocalTime.now();

        return items.stream()
                .filter(item -> {
                    if (item.getType() == ItemType.ICED_COFFEE) {
                        return currentTime.isBefore(LocalTime.of(15, 0));
                    }

                    if (item.getType()==ItemType.ICED_COFFEE && now.isAfter(LocalTime.of(15,0)) ){
                        items.remove(item);
                        throw new BusinessException(BusinessException.ErrorTyle.ICED_COFFEE_LOD);
                    }
                    return true;
                })
                .collect(Collectors.toList());
    }

    protected void validateBusinessRules(List<Item> items) {
        // 甜品不能单独购买
        boolean hasOnlyDesserts = items.stream()
                .allMatch(item -> item.getType() == ItemType.DESSERT);
        if (hasOnlyDesserts) {
            throw new BusinessException(BusinessException.ErrorTyle.DESSERT_ALONE);
        }

        // 必须包含至少一个主食
        boolean hasMainCourse = items.stream()
                .anyMatch(item -> item.getType() == ItemType.MAIN);
        if (!hasMainCourse) {
            throw new BusinessException(BusinessException.ErrorTyle.NO_MAIN_DISH);
        }


    }

    protected double calculateTotalPrice(List<Item> items, boolean isVIP) {
        double originalTotal = items.stream()
                .mapToDouble(Item::getPrice)
                .sum();

        // 应用套餐优惠
        double discountedTotal = applyComboDiscount(items, originalTotal);

        // 应用第二杯半价优惠
        discountedTotal = applyDrinkDiscount(items, discountedTotal);

        // 应用VIP折扣
        if (isVIP) {
            discountedTotal *= 0.9;
        }

        return discountedTotal;
    }


    protected double applyComboDiscount(List<Item> items, double total) {
        long burgerCount = items.stream()
                .filter(item -> "汉堡".equals(item.getName()))
                .count();
        long friesCount = items.stream()
                .filter(item -> "薯条".equals(item.getName()))
                .count();

        int comboCount = (int) Math.min(burgerCount, friesCount);
        if (comboCount > 0) {
            total -= comboCount * 5; // 每组套餐优惠5元
        }
        return total;
    }
    protected double applyDrinkDiscount(List<Item> items, double total) {
        Map<String, List<Item>> drinksByName = items.stream()
                .filter(item -> item.getType() == ItemType.DRINK)
                .collect(Collectors.groupingBy(Item::getName));

        for (List<Item> drinkGroup : drinksByName.values()) {
            if (drinkGroup.size() >= 2) {
                int discountPairs = drinkGroup.size() / 2;
                double discount = drinkGroup.get(0).getPrice() * 0.5 * discountPairs;
                total -= discount;
            }
        }
        return total;
    }

    @Override
    public void cancelOrder(String orderId, LocalDateTime currentTime ) throws BusinessException {
   //获取订单
    Order order=repository.findById(orderId);
    if (order==null){
        throw new BusinessException(BusinessException.ErrorTyle.ORDER_NOT_FOUND);

    }
    //订单状态已支付的订单不可以取消
        if (order.getStatus() == OrderStatus.PAID) {
            throw new IllegalStateException("已支付的订单不可取消");
        }
    // 如果订单未支付，可以取消订单
        if (order.getStatus()==OrderStatus.CANCCELLED){
            return;
        }
        // 3. 超时处理：创建超过30分钟的订单自动取消
        LocalDateTime now = LocalDateTime.now();
        Duration duration = Duration.between(order.getCreatetime(), now);
        if (duration.toMinutes() > 30) {
            order.setStatus(OrderStatus.CANCCELLED);
            order.setCreatetime(currentTime);
            repository.save(order);
            throw new BusinessException(BusinessException.ErrorTyle.ORDER_OVER_TIME);
        }
        // 正常取消订单
        order.setStatus(OrderStatus.CANCCELLED);
        order.setCreatetime(currentTime);
        repository.save(order);

        return;
    }

}